<template>
	<div class="content">
		<el-card class="box-card">
			<div class="tech-topView row mb-lg" @click="goBack">
				<i class="el-icon-back" />
				<div class="el-title-text">新增技师</div>
			</div>
			<el-tabs v-model="activeName" type="card">
				<el-tab-pane label="基础信息" name="first">
					<el-form :model="form" :rules="rules" ref="form" label-width="150px">
						<el-form-item label="头像" prop="technicianAvatar">
							<image-upload v-model="form.technicianAvatar" :limit="1" />
						</el-form-item>
						<el-form-item label="技师密码" prop="technicianPass">
							<el-input v-model="form.technicianPass" placeholder="请输入技师密码" class="elInput" />
						</el-form-item>

						<el-form-item label="技师类型" prop="technicianType">
							<el-select v-model="form.technicianType" placeholder="请选择">
								<el-option v-for="item in technicianTypeList" :key="item.id" :label="item.typeName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="性别" prop="technicianSex">
							<el-radio-group v-model="form.technicianSex">
								<el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value"
									:label="parseInt(dict.value)">{{dict.label}}</el-radio>
							</el-radio-group>
						</el-form-item>


						<el-form-item label="关联用户" prop="userName">
							<el-input v-if="form.id" v-model="form.userName" placeholder="请输入关联用户" class="elInput"
								:disabled='true' />
							<!-- <el-select v-model="form.userId" placeholder="请输入关联用户" clearable v-else>
								<el-option v-for="dict in selectUserList" :key="dict.userId" :label="dict.userName"
									:value="dict.userId" />
							</el-select> -->

							<div class="row">
								{{form.userName ? form.userName : '-'}}
								<el-button type="primary" size="small" @click="showUserDig" class="ml-mb">
									关联用户
								</el-button>
							</div>
						</el-form-item>
						<el-form-item label="技师姓名" prop="technicianName">
							<el-input v-model="form.technicianName" placeholder="请输入技师姓名" class="elInput" />
						</el-form-item>

						<el-form-item label="技师手机号" prop="technicianTel">
							<el-input v-model="form.technicianTel" placeholder="请输入技师手机号" class="elInput" />
						</el-form-item>
						<!-- <el-form-item label="意向工作城市" prop="serviceCity">
							<el-input v-model="form.serviceCity" placeholder="请输入意向工作城市" class="elInput" />
						</el-form-item> -->
						<el-form-item label="所属经纪人" prop="technicianInvitedCode">
							<el-select v-model="form.technicianInvitedCode" placeholder="请选择">
								<el-option v-for="item in brokerList" :key="item.brokerInvitationCode"
									:label="item.brokerName" :value="item.brokerInvitationCode">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="挂靠门店" prop="merchantId">
							<el-select v-model="form.merchantId" placeholder="请选择">
								<el-option v-for="item in merchantList" :key="item.id" :label="item.merchantName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<!-- <el-form-item label="在线状态" prop="isOnline">
							<el-radio-group v-model="form.isOnline">
								<el-radio v-for="dict in dict.type.is_online" :key="dict.value"
									:label="parseInt(dict.value)">{{dict.label}}</el-radio>
							</el-radio-group>
						</el-form-item> -->
						<!-- <el-form-item label="所在地址" prop="serviceCity">
							<el-input v-model="form.serviceCity" placeholder="请输入所在地址" class="elInput" />
						</el-form-item> -->
						<el-form-item label="白天免费距离" prop="dayFreeTolls">
							<el-input v-model="form.dayFreeTolls" placeholder="请输入白天免费距离" class="elInput">
								<template slot="append">km</template>
							</el-input>
						</el-form-item>

						<el-form-item label="晚上免费距离" prop="nightFreeTolls">
							<el-input v-model="form.nightFreeTolls" placeholder="请输入晚上免费距离" class="elInput">
								<template slot="append">km</template>
							</el-input>
						</el-form-item>
						<el-form-item label="服务距离" prop="serviceDistance">
							<el-input v-model="form.serviceDistance" placeholder="请输入服务距离" class="elInput">
								<template slot="append">km</template>
							</el-input>
						</el-form-item>
						<!-- <el-form-item label="经度" prop="longitude">
							<el-input v-model="form.longitude" placeholder="请输入经度" class="elInput" />
						</el-form-item>
						<el-form-item label="纬度" prop="latitude">
							<el-input v-model="form.latitude" placeholder="请输入纬度" class="elInput" />

							<el-button type="primary" @click="getLongitudeLatitude">获取经纬度</el-button>
						</el-form-item> -->
						<div class="lb-goods-edit-classify mb-lg row">
							<div class="title">技师提成比例</div>
							<span class="tips">对于新进平台的技师，且综合素质较好的，可以设置某个阶段固定高提成比例。提成比例和提成限期时间不填写，则默认走统一的浮动比例</span>
						</div>
						<el-form-item label="提成比例" prop="splitRate">
							<el-input v-model="form.splitRate" placeholder="请输入提成比例" class="elInput">
								<template slot="append">%</template>
							</el-input>
						</el-form-item>
						<el-form-item label="升级套餐分成比例" prop="upgradeSplitRate">
							<el-input v-model="form.upgradeSplitRate" placeholder="请输入加钟基础值" class="elInput">
								<template slot="append">%</template>
							</el-input>
						</el-form-item>
						<el-form-item label="第一次加钟分成比例" prop="bellFirstSplitRate">
							<el-input v-model="form.bellFirstSplitRate" placeholder="请输入加钟基础值" class="elInput">
								<template slot="append">%</template>
							</el-input>
						</el-form-item>
						<el-form-item label="第二次加钟分成比例" prop="bellSecondSplitRate">
							<el-input v-model="form.bellSecondSplitRate" placeholder="请输入加钟基础值" class="elInput">
								<template slot="append">%</template>
							</el-input>
						</el-form-item>
						<el-form-item label="生效开始日期" prop="effectStartTime">
							<el-date-picker clearable v-model="form.effectStartTime" type="datetime"
								value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择生效开始日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="生效结束日期" prop="effectEndTime">
							<el-date-picker clearable v-model="form.effectEndTime" type="datetime"
								value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择生效结束日期">
							</el-date-picker>
						</el-form-item>
						<div class="lb-goods-edit-classify mb-lg row">
							<div class="title">其他信息</div>
						</div>
						<el-form-item label="技师简介" prop="technicianIntro">
							<el-input type="textarea" placeholder="请输入内容" v-model="form.technicianIntro" maxlength="300"
								show-word-limit class="elInput" />
						</el-form-item>
						<el-form-item label="身份证号" prop="idCard">
							<el-input v-model="form.idCard" placeholder="请输入身份证号" class="elInput" />
						</el-form-item>
						<!-- <el-form-item label="年龄" prop="technicianAge">
							<el-input v-model="form.technicianAge" placeholder="请输入年龄" class="elInput" />
						</el-form-item>
						<el-form-item label="出生年份" prop="technicianYear">
							<el-input v-model="form.technicianYear" placeholder="请输入出生年份" class="elInput" />
						</el-form-item> -->
						<el-form-item label="生活照片" prop="lifePhoto">
							<image-upload v-model="form.lifePhoto" />
						</el-form-item>
						<el-form-item label="民族" prop="technicianEthnic">
							<el-input v-model="form.technicianEthnic" placeholder="请输入民族" class="elInput" />
						</el-form-item>
						<el-form-item label="身高" prop="technicianHeight">
							<el-input v-model="form.technicianHeight" placeholder="请输入身高" class="elInput">
								<template slot="append">cm</template>
							</el-input>
						</el-form-item>
						<el-form-item label="体重" prop="technicianWeight">
							<el-input v-model="form.technicianWeight" placeholder="请输入体重" class="elInput">
								<template slot="append">kg</template>
							</el-input>
						</el-form-item>
						<!-- <el-form-item label="身高" prop="technicianHeight">
							<el-input v-model="form.technicianHeight" placeholder="请输入身高" class="elInput" />
						</el-form-item> -->
						<!-- <el-form-item label="体重" prop="technicianWeight">
							<el-input v-model="form.technicianWeight" placeholder="请输入体重" class="elInput" />
						</el-form-item> -->
						<el-form-item label="评分" prop="mark">
							<el-input v-model="form.mark" placeholder="请输入评分" class="elInput" />
							<div class="tips">范围:0-5(最高5分)</div>
						</el-form-item>
						<el-form-item label="关联服务">
							<el-button type="primary" icon="el-icon-plus" @click="asociaBut" class="ml-mb">
								关联服务
							</el-button>
						</el-form-item>
					</el-form>
					<div v-if="allIds.length">
						<el-table v-loading="loading" :data="selectItem" class="elTable">
							<el-table-column label="ID" align="center" prop="id" />
							<el-table-column label="封面图" align="center" prop="mark">
								<template slot-scope="scope">
									<image-preview :src="scope.row.itemMainPicture" :width="50" :height="50" />
								</template>
							</el-table-column>
							<el-table-column label="服务名称" align="center" prop="itemName" />
							<el-table-column label="服务价格" align="center" prop="itemPrice" />
							<el-table-column label="服务会员价格" align="center" prop="itemMemberPrice" />
							<el-table-column label="服务时长" align="center" prop="itemTime">
								<template slot-scope="scope">
									{{scope.row.itemTime}}分钟
								</template>
							</el-table-column>
							<el-table-column label="操作" align="center" class-name="small-padding fixed-width"
								fixed="right">
								<template slot-scope="scope">
									<el-button type="danger" plain size="small "
										@click="spaceDelete(scope.row)">取消关联</el-button>
								</template>
							</el-table-column>
						</el-table>
						<pagination v-show="techTotal>0" :total="techTotal" :page.sync="techParams.pageNum"
							:limit.sync="techParams.pageSize" @pagination="selectFromList" />

					</div>
					<div class="dialog-footer">
						<el-button type="primary" @click="submitForm">提 交</el-button>
						<el-button @click="goBack">取 消</el-button>
					</div>
				</el-tab-pane>
			</el-tabs>
		</el-card>

		<el-dialog :title="title" :visible.sync="asOpen" width="1000px" append-to-body center>
			<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
				label-width="68px">
				<el-form-item label="项目名称" prop="keyWord">
					<el-input v-model="queryParams.keyWord" placeholder="请输入项目名称" clearable
						@keyup.enter.native="handleQuery" class="elInput" />
					<el-form-item class="ml-mb">
						<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
						<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form-item>
			</el-form>
			<el-table v-loading="loading" :data="routineItemList" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="ID" align="center" prop="id" />
				<el-table-column label="封面图" align="center" prop="mark">
					<template slot-scope="scope">
						<image-preview :src="scope.row.itemMainPicture" :width="50" :height="50" />
					</template>
				</el-table-column>
				<el-table-column label="服务名称" align="center" prop="itemName" />
				<el-table-column label="服务价格" align="center" prop="itemPrice" />
				<el-table-column label="服务会员价格" align="center" prop="itemMemberPrice" />
				<el-table-column label="服务时长" align="center" prop="itemTime">
					<template slot-scope="scope">
						{{scope.row.itemTime}}分钟
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="assTotal>0" :total="assTotal" :page.sync="queryParams.pageNum"
				:limit.sync="queryParams.pageSize" @pagination="assonItemList" />
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="assHaulds">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>


		<el-dialog :title="userTitle" :visible.sync="userOpen" width="60%" append-to-body center>
			<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
				label-width="68px">
				<el-form-item label="手机号" prop="keyWord">
					<el-input v-model="queryParams.keyWord" placeholder="请输入手机号" clearable
						@keyup.enter.native="handleQuery" class="elInput" />
					<el-form-item class="ml-mb">
						<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
						<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form-item>
			</el-form>

			<el-table v-loading="loading" :data="selectUserList">
				<el-table-column label="ID" align="center" prop="userId" />
				<el-table-column label="头像" align="center" prop="userAvatar">
					<template slot-scope="scope">
						<image-preview :src="scope.row.userAvatar" :width="50" :height="50" />
					</template>
				</el-table-column>
				<el-table-column label="昵称" align="center" prop="userName" />
				<el-table-column label="手机号" align="center" prop="userTel" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button size="mini" type="text" @click="choseUser(scope.row)"
							v-hasPermi="['equity:UserCoupon:edit']">选择</el-button>

					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="useTotal>0" :total="useTotal" :page.sync="queryParams.pageNum"
				:limit.sync="queryParams.pageSize" @pagination="UserItemTech" />
		</el-dialog>
	</div>
</template>

<script>
	import {
		addTechnician,
		selectAddTechItem,
		selectIsTechItem,
		selectUserTechItem
	} from "@/api/technician/technician";
	import {
		listTechnicianType
	} from "@/api/technicianType/technicianType";
	import {
		listBroker
	} from "@/api/broker/broker";
	import {
		listMerchant
	} from "@/api/merchant/merchant";
	export default {
		dicts: ['sys_user_sex', 'is_online'],
		data() {
			return {
				// 选中数组
				ids: [],
				allIds: [],
				// 显示搜索条件
				showSearch: true,
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				activeName: 'first',
				// 技师类型表格数据
				technicianTypeList: [],
				// 所属经纪人
				brokerList: [],
				// 挂靠门店
				merchantList: [],
				// 弹出层标题
				techTotal: 0,
				assTotal: 0,
				title: "",
				asOpen: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					keyWord: null,
					itemIds: [],
				},
				techParams: {
					pageNum: 1,
					pageSize: 10,
				},
				// 服务项目表格数据
				routineItemList: [],
				selectItem: [], //选中数据
				selectUserList: [],

				userTitle: '',
				userOpen: false,
				useTotal: 0,
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					technicianName: [{
						required: true,
						message: "技师姓名不能为空",
						trigger: "blur"
					}],
					technicianAvatar: [{
						required: true,
						message: "技师头像不能为空",
						trigger: "blur"
					}],
					technicianPass: [{
						required: true,
						message: "密码不能为空",
						trigger: "blur"
					}],
					technicianSex: [{
						required: true,
						message: "性别不能为空",
						trigger: "blur"
					}],
					technicianTel: [{
						required: true,
						message: "技师手机号不能为空",
						trigger: "blur"
					}],
					isOnline: [{
						required: true,
						message: "在线状态不能为空",
						trigger: "change"
					}],
					idCard: [{
						required: true,
						message: "技师身份证不能为空",
						trigger: "change"
					}],
					mark: [{
						required: true,
						message: "技师身份证不能为空",
						trigger: "change"
					}],
				}
			};
		},
		created() {
			this.techTypeList()
			this.brokeList()
			this.merchList()
			this.UserItemTech()
		},
		methods: {
			reset() {
				this.form = {
					id: null,
					technicianType: null,
					technicianName: null,
					technicianAvatar: null,
					technicianTel: null,
					isOnline: null,
					technicianIdentity: null,
					merchantId: null,
					userId: null,
					technicianSex: null,
					technicianAge: null,
					openId: null,
					unionid: null,
					technicianPass: null,
					idCard: null,
					technicianYear: null,
					longitude: null,
					latitude: null,
					serviceItem: null,
					mark: null,
					orderReceivingTime: null,
					orderReceiving: null,
					lifePhoto: null,
					technicianEthnic: null,
					technicianHeight: null,
					technicianWeight: null,
					technicianIntro: null,
					dayFreeTolls: null,
					nightFreeTolls: null,
					serviceDistance: null,
					totalRevenue: null,
					onlineTime: null,
					gradeId: null,
					serviceCity: null,
					technicianInvitationCode: null,
					technicianInvitedCode: null,
					technicianSource: null,
					splitRate: null,
					upgradeSplitRate: null,
					bellFirstSplitRate: null,
					bellSecondSplitRate: null,
					effectStartTime: null,
					effectEndTime: null,
					isDelete: null,
					createTime: null,
					updateTime: null
				};
				this.resetForm("form");
			},
			queryReset() {
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
					keyWord: null,
				}
			},
			/** 查询技师类型列表 */
			techTypeList() {
				this.loading = true;
				listTechnicianType(this.queryParams).then(response => {
					this.technicianTypeList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			UserItemTech() {
				selectUserTechItem(this.queryParams).then(response => {
					this.selectUserList = response.rows;
					this.useTotal = response.total
				});
			},
			/** 查询经纪人数据列表 */
			brokeList() {
				this.loading = true;
				listBroker(this.queryParams).then(response => {
					this.brokerList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 查询商家管理列表 */
			merchList() {
				this.loading = true;
				listMerchant(this.queryParams).then(response => {
					this.merchantList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},

			// 关联服务按钮
			asociaBut() {
				this.queryReset()
				this.routineItemList = []
				this.title = '添加服务'
				this.asOpen = true;
				this.assonItemList()
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.assonItemList();
				this.UserItemTech()
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			// 添加服务
			/** 查询服务项目列表 */
			assonItemList() {
				this.loading = true;
				this.queryParams.itemIds = this.unique(this.allIds)
				selectAddTechItem(this.queryParams).then(response => {
					this.routineItemList = response.rows
					this.assTotal = response.total;
					this.loading = false;
				});
			},
			// 添加技师确认按钮
			assHaulds() {
				this.allIds.push(...this.ids)
				this.selectFromList()
				this.asOpen = false
			},

			selectFromList() {
				this.loading = true;
				this.techParams.itemIds = this.unique(this.allIds)
				selectIsTechItem(this.techParams).then(response => {
					this.selectItem = response.rows;
					this.techTotal = response.total;
					this.loading = false;
				});
			},

			// 取消按钮
			cancel() {
				this.open = false;
				this.asOpen = false
				this.queryReset()
			},
			/** 提交按钮 */
			submitForm() {

				if (this.form.mark > 5) {
					this.form.mark = null
					this.$modal.msgWarning("请输入正确评分");
				}
				if (this.form.serviceItem) this.techParams.itemIds.join(",");
				else this.form.serviceItem = ''
				console.log(this.form.serviceItem)
				this.form.isOnline = 0
				this.$refs["form"].validate(valid => {
					if (valid) {
						addTechnician(this.form).then(response => {
							this.$modal.msgSuccess("新增成功");
							this.goBack()
						});
					}
				});
			},
			spaceDelete(row) {
				this.allIds.find((item, index) => {
					if (row.id == item) this.allIds.splice(index, 1)
				})
				this.selectFromList()
			},
			goBack() {
				this.$commonJs.backRou()
			},
			unique(arr) {
				const res = new Map();
				return arr.filter((a) => !res.has(a) && res.set(a, 1))
			},
			showUserDig() {
				this.queryReset()
				this.userTitle = '关联用户'
				this.userOpen = true
			},
			choseUser(row) {
				this.form.userId = row.userId
				this.form.userName = row.userName
				this.userOpen = false
			},
			getLongitudeLatitude() {
				//如果该对象存在，那么地理位置服务可用。
				if ('geolocation' in navigator) {
					/* 地理位置服务可用 */
					var options = {
						enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
						timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
						maximumAge: 0 //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
					}

					function success(position) {
						//position.coords (只读) 返回一个定义了当前位置的Coordinates对象。
						//position.timestamp (只读) 返回一个时间戳DOMTimeStamp， 这个时间戳表示获取到的位置的时间。
						var lat = position.coords.latitude //当前位置的纬度
						var lng = position.coords.longitude //当前位置精度
					}

					function error(err) {
						var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时']
						console.log(errorType[err.code - 1])
					}

					navigator.geolocation.getCurrentPosition(success, error, options)
				} else {
					/* 地理位置服务不可用 */
					console.log('无法获取您的位置，请检查定位是否开启或刷新重试')
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.mb-lg {
		margin-bottom: 15px;
	}

	.ml-mb {
		margin-left: 20px;
	}

	.box-card {
		margin: 20px;
	}

	.elInput {
		width: 300px;
	}

	.tips {
		color: #fe6c6f;
		font-size: 12px;
	}


	.tech-topView {
		border-bottom: 1px solid #e1e1e1;
		padding-bottom: 10px;

		.el-title-text {
			font-size: 14px;
			color: #666;
			margin-left: 10px;
		}
	}

	.lb-goods-edit-classify {
		width: 100%;
		border-top: 1px solid #eff2f6;
		display: -webkit-box;
		display: -ms-flexbox;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;

		.title {
			display: inline-block;
			padding: 6px 15px;
			color: #609beb;
			background: #f5f7fa;
			margin-right: 10px;
			font-size: 14px;
		}


	}

	.item .el-form-item__label {
		text-align: right;
		vertical-align: middle;
		float: left;
		font-size: 14px;
		color: #606266;
		line-height: 40px;
		padding: 0 12px 0 0;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		font-weight: 500 !important;
	}

	label {
		z-index: 111;
		font-weight: 500 !important;
	}
</style>